﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using JESAI.Core;
using JESAI.Core.Builders;
using JESAI.Core.Reflection;
using JESAI.Core.Util;
using JESAI.Core.Util.Helpers;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// 服务集合 - 应用程序 扩展
/// </summary>
public static class ServiceCollectionApplicationExtensions
{
    /// <summary>
    /// 创建<see cref="IJESAIBuilder"/>，开始构建JESAI服务
    /// </summary>
    /// <param name="services">服务集合</param>
    public static IJESAIBuilder AddJESAI(this IServiceCollection services)
    {
        Check.NotNull(services, nameof(services));
        var configuration = services.GetConfiguration();
        Singleton<IConfiguration>.Instance = configuration;

        // 初始化所有程序集查找器
        services.TryAddSingleton<IAllAssemblyFinder>(new AppDomainAllAssemblyFinder());

        var builder = services.GetSingletonInstanceOrNull<IJESAIBuilder>() ?? new JESAIBuilder(services);
        services.TryAddSingleton<IJESAIBuilder>(builder);

        builder.AddCoreModule();
     
        JESAILoader.RegisterTypes(services);
        return builder;
    }
}
